"""
完成业务接口描述
每个方法返回接口的响应对象
"""
import requests
from jsonpath import jsonpath

from frame.apis.wework import Wework


class Departments(Wework):

    def create(self, data):
        """
        创建部门接口
        :return:
        """
        create_url = f"{self.base_url}/cgi-bin/department/create?access_token={self.token}"
        # r = requests.post(create_url, json=data)
        req = {
            "method": "POST",
            "url": create_url,
            "json": data
        }
        r = self.send_api(req)
        return r

    def update(self, data):
        """
        更新部门接口
        :return:
        """
        update_url = f"{self.base_url}/cgi-bin/department/update?access_token={self.token}"
        # r = requests.post(update_url, json=data)
        req = {
            "method": "POST",
            "url": update_url,
            "json": data
        }
        r = self.send_api(req)
        return r

    def get(self):
        """
        获取子部门 ID 列表接口
        :return:
        """
        list_url = f"{self.base_url}/cgi-bin/department/simplelist?access_token={self.token}"
        # r = requests.get(list_url)
        req = {
            "method": "GET",
            "url": list_url,
        }
        r = self.send_api(req)
        return r

    def delete(self, depart_id):
        """
        删除部门接口
        :return:
        """
        delete_url = f"{self.base_url}/cgi-bin/department/delete?access_token={self.token}&id={depart_id}"
        # r = requests.get(delete_url)
        req = {
            "method": "GET",
            "url": delete_url,
        }
        r = self.send_api(req)
        return r

    def clear(self):
        """
        清理除去父部门之外，已存在的部门
        :return:
        """
        # 获取所有部门的 id
        r = self.get()
        ids = jsonpath(r.json(), "$..id")
        for i in ids:
            if i != 1:
                self.delete(i)



